<template>
  <div class="pic-management">
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span>轮播图管理</span>
        <el-button 
          type="primary" 
          size="small" 
          icon="el-icon-plus" 
          @click="handleAddPic">
          添加轮播图
        </el-button>
      </div>
      
      <div class="search-bar">
        <el-input
          placeholder="标题"
          v-model="searchParams.title"
          class="search-input"
          clearable
          @clear="handleSearch">
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
      
      <el-table
        v-loading="loading"
        :data="this.filteredPicList"
        style="width: 100%"
        border>
        <el-table-column
          type="index"
          label="#"
          width="80"
          align="center">
        </el-table-column>
        <el-table-column
          prop="image"
          label="图片"
          width="150"
          align="center">
          <template slot-scope="scope">
            <el-image 
              style="width: 120px; height: 80px" 
              :src="scope.row.image" 
              fit="cover"
              :preview-src-list="[scope.row.image]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题">
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isShow ? 'success' : 'info'">
              {{ scope.row.isShow ? '展示中' : '未展示' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="300"
          align="center">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button
                size="mini"
                type="success"
                icon="el-icon-view"
                @click="handlePreviewPic(scope.row)">预览</el-button>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleEditPic(scope.row)">编辑</el-button>
              <el-button
                v-if="!scope.row.isShow"
                size="mini"
                type="warning"
                icon="el-icon-star-on"
                @click="handleShowPic(scope.row)">展示</el-button>
              <el-button
                v-else
                size="mini"
                type="info"
                icon="el-icon-star-off"
                @click="handleFadePic(scope.row)">取消展示</el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDeletePic(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 添加/编辑轮播图对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加轮播图' : '编辑轮播图'"
      :visible.sync="picDialogVisible"
      width="600px">
      <el-form 
        ref="picForm" 
        :model="picForm" 
        :rules="picRules" 
        label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="picForm.title" placeholder="请输入轮播图标题"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            type="textarea" 
            :rows="3" 
            v-model="picForm.description" 
            placeholder="请输入轮播图描述">
          </el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload
            class="pic-uploader"
            action="/api/sys/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforePicUpload">
            <img v-if="picForm.image" :src="picForm.image" class="pic-preview">
            <i v-else class="el-icon-plus pic-uploader-icon"></i>
          </el-upload>
          <div class="pic-tip">建议尺寸: 1920px × 600px，大小不超过2MB</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="picDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPicForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 预览轮播图对话框 -->
    <el-dialog
      title="轮播图预览"
      :visible.sync="previewDialogVisible"
      width="800px"
      center>
      <div class="preview-container">
        <img :src="previewImage" class="preview-image">
        <div class="preview-info">
          <h3 class="preview-title">{{ previewTitle }}</h3>
          <p class="preview-desc">{{ previewDesc }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from '@/utils/http';

export default {
  name: 'PicManagement',
  data() {
    return {
      searchParams: {
        title: ''
      },
      loading: false,
      picList: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      picDialogVisible: false,
      dialogType: 'add', // 'add' 或 'edit'
      picForm: {
        id: '',
        title: '',
        description: '', // 使用description而不是desc
        image: ''
      },
      picRules: {
        title: [
          { required: true, message: '请输入轮播图标题', trigger: 'blur' },
          { max: 50, message: '标题长度不能超过50个字符', trigger: 'blur' }
        ],
        description: [ // 将desc改为description
          { max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请上传轮播图图片', trigger: 'change' }
        ]
      },
      submitting: false,
      previewDialogVisible: false,
      previewImage: '',
      previewTitle: '',
      previewDesc: '',
      showPicIds: new Set() // 存储展示中的轮播图ID
    };
  },
  computed: {
    filteredPicList() {
      // 如果后端已实现分页，直接返回 picList
      if (this.pagination.total > 0) {
        return this.picList;
      }
      
      // 过滤标题
      let filtered = this.picList;
      if (this.searchParams.title) {
        const keyword = this.searchParams.title.toLowerCase();
        filtered = filtered.filter(pic => 
          pic.title && pic.title.toLowerCase().includes(keyword)
        );
      }
      
      // 更新总数
      this.pagination.total = filtered.length;
      
      // 前端分页
      const startIndex = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const endIndex = startIndex + this.pagination.pageSize;
      return filtered.slice(startIndex, endIndex);
    }
  },
  created() {
    this.fetchPicList();
    this.fetchShowPics();
  },
  methods: {
    // 获取轮播图列表
    async fetchPicList() {
      this.loading = true;
      try {
        const res = await httpInstance.get('/api/pic');
        
        if (res.code === 200) {
          this.picList = res.data || [];
          
          // 标记展示状态
          this.picList.forEach(pic => {
            // 检查是否有isShow属性，如果没有则根据showPicIds判断
            if (pic.isShow === undefined) {
              pic.isShow = this.showPicIds.has(pic.id);
            }
          });
          
          this.pagination.total = this.picList.length;
        } else {
          this.$message.error(res.msg || '获取轮播图列表失败');
        }
      } catch (error) {
        console.error('获取轮播图列表失败:', error);
        this.$message.error('获取轮播图列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 获取展示中的轮播图
    async fetchShowPics() {
      try {
        const res = await httpInstance.post('/api/pic/getAllShow');
        
        if (res.code === 200) {
          // 清空并重新添加展示中的ID
          this.showPicIds.clear();
          (res.data || []).forEach(pic => {
            this.showPicIds.add(pic.id);
          });
          
          // 更新列表中的展示状态
          this.picList.forEach(pic => {
            pic.isShow = this.showPicIds.has(pic.id);
          });
        }
      } catch (error) {
        console.error('获取展示中的轮播图失败:', error);
      }
    },
    
    // 处理前端分页
    handleFrontendPagination() {
      // 在 computed 属性中已处理
    },
    
    // 处理搜索
    handleSearch() {
      this.pagination.currentPage = 1;
    },
    
    // 处理页码大小变化
    handleSizeChange(newSize) {
      this.pagination.pageSize = newSize;
    },
    
    // 处理页码变化
    handleCurrentChange(newPage) {
      this.pagination.currentPage = newPage;
    },
    
    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 处理添加轮播图
    handleAddPic() {
      this.dialogType = 'add';
      this.picForm = {
        id: '',
        title: '',
        description: '', // 使用description而不是desc
        image: ''
      };
      this.picDialogVisible = true;
      
      // 延迟重置表单，确保DOM更新后操作
      this.$nextTick(() => {
        this.$refs.picForm && this.$refs.picForm.clearValidate();
      });
    },
    
    // 处理编辑轮播图
    handleEditPic(row) {
      this.dialogType = 'edit';
      this.picForm = {
        id: row.id,
        title: row.title,
        description: row.desc, // 将desc映射到description
        image: row.image
      };
      this.picDialogVisible = true;
      
      // 延迟重置表单，确保DOM更新后操作
      this.$nextTick(() => {
        this.$refs.picForm && this.$refs.picForm.clearValidate();
      });
    },
    
    // 处理预览轮播图
    handlePreviewPic(row) {
      this.previewImage = row.image;
      this.previewTitle = row.title;
      this.previewDesc = row.desc;
      this.previewDialogVisible = true;
    },
    
    // 处理删除轮播图
    async handleDeletePic(row) {
      try {
        await this.$confirm(`确定要删除轮播图 "${row.title}" 吗? 此操作不可恢复!`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const res = await httpInstance.post(`/api/pic/del/${row.id}`);
        
        if (res.code === 200) {
          this.$message.success('轮播图删除成功');
          // 如果是展示中的轮播图，从展示列表中移除
          if (this.showPicIds.has(row.id)) {
            this.showPicIds.delete(row.id);
          }
          this.fetchPicList();
        } else {
          this.$message.error(res.msg || '删除轮播图失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除轮播图失败:', error);
          this.$message.error('删除轮播图失败');
        }
      }
    },
    
    // 处理展示轮播图
    async handleShowPic(row) {
      try {
        const res = await httpInstance.post(`/api/pic/show/${row.id}`);
        
        if (res.code === 200) {
          this.$message.success('轮播图已设置为展示');
          this.showPicIds.add(row.id);
          row.isShow = true;
        } else {
          this.$message.error(res.msg || '设置展示失败');
        }
      } catch (error) {
        console.error('设置展示失败:', error);
        this.$message.error('设置展示失败');
      }
    },
    
    // 处理取消展示轮播图
    async handleFadePic(row) {
      try {
        const res = await httpInstance.post(`/api/pic/fade/${row.id}`);
        
        if (res.code === 200) {
          this.$message.success('已取消轮播图展示');
          this.showPicIds.delete(row.id);
          row.isShow = false;
        } else {
          this.$message.error(res.msg || '取消展示失败');
        }
      } catch (error) {
        console.error('取消展示失败:', error);
        this.$message.error('取消展示失败');
      }
    },
    
    // 处理图片上传成功
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.picForm.image = res.data;
        // 设置图片验证通过
        this.$refs.picForm.validateField('image');
      } else {
        this.$message.error(res.msg || '上传图片失败');
      }
    },
    
    // 上传图片前的验证
    beforePicUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    
    // 提交轮播图表单
    submitPicForm() {
      this.$refs.picForm.validate(async (valid) => {
        if (!valid) return;
        
        this.submitting = true;
        try {
          // 创建一个新对象，将description映射回desc
          const picData = { 
            id: this.picForm.id,
            title: this.picForm.title,
            description: this.picForm.description, // 将description映射回desc
            image: this.picForm.image
          };
          
          let res;
          
          if (this.dialogType === 'add') {
            // 添加轮播图
            res = await httpInstance.post('/api/pic/add', picData);
          } else {
            // 编辑轮播图
            res = await httpInstance.post('/api/pic/update', picData);
          }
          
          if (res.code === 200) {
            this.$message.success(this.dialogType === 'add' ? '轮播图添加成功' : '轮播图更新成功');
            this.picDialogVisible = false;
            this.fetchPicList();
          } else {
            this.$message.error(res.msg || (this.dialogType === 'add' ? '添加轮播图失败' : '更新轮播图失败'));
          }
        } catch (error) {
          console.error(this.dialogType === 'add' ? '添加轮播图失败:' : '更新轮播图失败:', error);
          this.$message.error(this.dialogType === 'add' ? '添加轮播图失败' : '更新轮播图失败');
        } finally {
          this.submitting = false;
        }
      });
    }
  }
};
</script>

<style scoped>
.pic-management {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 5px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pic-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
}

.pic-uploader:hover {
  border-color: #409EFF;
}

.pic-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.pic-preview {
  width: 300px;
  height: 150px;
  display: block;
  object-fit: cover;
}

.pic-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-image {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.preview-info {
  width: 100%;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-title {
  font-size: 18px;
  color: #303133;
  margin-bottom: 10px;
}

.preview-desc {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}
</style>